// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import MeshRender2D from "./libs/MeshRender2D";


const { ccclass, property, executeInEditMode, menu } = cc._decorator;

@ccclass
@executeInEditMode
@menu("Mesh/RectMesh")
export default class RectMesh extends cc.Component {
    private _topVertexs: cc.Vec2[] = [];
    private _bottomVertexs: cc.Vec2[] = [];
    private _total = 50;
    private _w = 200;
    private _h = 100;
    private _a = 10;
    private _ww = 10;
    private _elapsed = 0;
    private _mesh: MeshRender2D;
    onLoad() {
        this._mesh = this.node.getComponent(MeshRender2D);
        let deltaW = this._w / this._total;
        let deltaH = this._h / this._total;
        let hW = this._w * 0.5;
        let hH = this._h * 0.5;

        for (let i = 0, len = this._total; i <= len; i++) {
            this._topVertexs.push(cc.v2(-hW + i * deltaW, hH));
            this._bottomVertexs.push(cc.v2(-hW + i * deltaW, -hH));
        }

        let vertexs = [];
        for (let i = 0, len = this._total; i <= len; i++) {
            vertexs.push(this._topVertexs[i].clone());
            vertexs.push(this._bottomVertexs[i].clone());
        }

        this._mesh.vertexs = vertexs;

        let indices = [];
        for (let i = 0, len = this._total; i < len; i++) {
            indices.push(i * 2);
            indices.push(i * 2 + 1);
            indices.push(i * 2 + 3);

            indices.push(i * 2 + 2);
            indices.push(i * 2);
            indices.push(i * 2 + 3);
        }

        this._mesh.indices = indices;
    }

    protected update(dt: number): void {
        this._elapsed += dt;

        for (let i = 0, len = this._total; i <= len; i++) {
            let offset = Math.sin(this._elapsed * this._ww + i);
            let pos = this._mesh.vertexs[i * 2];
            pos.set(cc.Vec2.UP);
            pos.mulSelf(offset).addSelf(this._topVertexs[i]);
        }
        this._mesh["setVertsDirty"]();
    }
}
